package com.sx.micowell.module.sport

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayerView
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.miloyu.modelnet.response.TrainSelectData
import com.miloyu.modelnet.response.getUrl
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.ActSportBinding
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.MyApplication
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.model.SportModel
import com.sx.micowell.framework.serialPort.SerialPortActivity
import com.sx.micowell.framework.tools.cmd.CmdException
import com.sx.micowell.framework.view.chartManager.initUi
import com.sx.micowell.framework.view.chartManager.scaleX_OBJ
import com.sx.micowell.framework.view.chartManager.setNetData
import com.sx.micowell.framework.view.dialog.DialogException
import com.sx.widget.app.dialog.BaseDialog
import tv.danmaku.ijk.media.player.IMediaPlayer
import kotlin.streams.toList

/**
 * @Description
 * @Author 梁浩文
 * @Date 2021/9/2 9:48
 */
class SportActivity : SerialPortActivity<ActSportBinding>() {
    @Autowired(name = IntentKey.DATA)
    @JvmField
    var data: String = ""

    private lateinit var player: PlayerView

    private val viewModel: SportModel by lazy {
        getActivityScopeViewModel(SportModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig =
        DataBindingConfig(R.layout.act_sport, BR.viewModel, viewModel)

    override fun initView() {
        ImmersionBar.with(this).titleBar(findViewById(R.id.app_video_box)).init()
        binding.sportChart.initUi()
        binding.sportChart.xAxis.setDrawLabels(false)
        binding.sportChart.xAxis.setLabelCount(2000, true)
    }

    fun initLineData() {
        var sportChart = binding.sportChart
        var netDataSet = sportChart.setNetData(null, viewModel.lineListData)
        when (viewModel.getModeType()) {
            IntentKey.OBSERVE -> {
                //观察者模式
                //恒等张力
                netDataSet.fillDrawable = getDrawableLine()
            }
            IntentKey.LINE_MODE -> {
                //极限 划船 高尔夫 链条
                netDataSet.setDrawFilled(false)
                netDataSet.setMode(LineDataSet.Mode.LINEAR)
            }
            IntentKey.POWER -> {
                //力量递增 递减
                netDataSet.setDrawFilled(true)
                netDataSet.setLineWidth(0f)
                netDataSet.fillColor = ContextCompat.getColor(this, R.color.them)
                netDataSet.setMode(LineDataSet.Mode.STEPPED)
            }
        }
        sportChart.data = LineData(netDataSet)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.sportList.observe(this) {
            if (it.size > 0) {
                setLineData(if (viewModel.chartTypeY == 0) it.stream().map { it.speed }
                    .toList() else it.stream().map { it.moment }.toList())
            }

        }
        viewModel.sendEvent.observe(this) {
            var power = viewModel.getPower()
            power?.let {
                send(viewModel.allCount!!.get() as Int, viewModel.getMode(), 0, power[0], power[1])
            }
        }
        viewModel.changeVideoUrlEvent.observe(this) {
            startPlay(it.getUrl())
        }
        viewModel.finishEvent.observe(this) {
            if (it) {
                stop()
                viewModel.finishSport()
            }
        }
        viewModel.errorFinishEvent.observe(this) {
            XPopup.Builder(SportActivity@ this)
                .asConfirm("上报异常", "请重新上报运动", "", "确定", object : OnConfirmListener {
                    override fun onConfirm() {
                        viewModel.finishSport()
                    }
                }, null, true)
                .also {
                    it.popupInfo.isDismissOnBackPressed=false
                    it.popupInfo.isDismissOnTouchOutside=false
                }
                .show()
        }


    }

    override fun initData() {
//        bufferSee(viewModel)
        var listData = mutableListOf<TrainSelectData>()
        listData.addAll(
            Gson().fromJson<List<TrainSelectData>>(
                data,
                object : TypeToken<List<TrainSelectData>>() {}.type
            )
        )
        viewModel.selectData = listData
        initLineData()
        initPlayer()
        viewModel.initVideo()
    }

    /**初始化播放视频*/
    fun initPlayer() {
        player = PlayerView(this)
            .setScaleType(PlayStateParams.fitparent)
            .setShowSpeed(false)
            .forbidTouch(false)
            .hideHideTopBar(true)
            .hideSteam(true)
            .hideFullscreen(false)
            .hideRotation(true)
            .hideBottonBar(false)
        player.setOnInfoListener(object : IMediaPlayer.OnInfoListener {
            override fun onInfo(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
                if (p1 == PlayStateParams.STATE_COMPLETED && !backGroup) {
                    //结束
                    player.startPlay()
                }
                return true
            }
        })

    }

    var backGroup = false

    /**开始播放视频*/
    fun startPlay(mp4: String) {
        player.setPlaySource(
            MyApplication.instance().getProxy(this)
                ?.getProxyUrl(mp4)
        ).startPlay()
        player?.setFullListener {
            backGroup = true
            RouteManager.getInstance().intentMkVideoVideo(mp4, "")
        }
    }


    fun setLineData(value: List<Int>) {
        if (binding != null && binding.sportChart != null) {
            var lineData = binding.sportChart.lineData
            lineData?.let {
                var lineDataSet = lineData.getDataSetByIndex(0) as LineDataSet
                lineDataSet?.let {
                    for (i in value) {
                        lineData.addEntry(Entry(it.entryCount.toFloat(), i.toFloat()), 0)
                    }
                    binding.sportChart.scaleX_OBJ((it.entryCount + 1) / 3)
                    binding.sportChart.notifyDataSetChanged()
                    binding.sportChart.moveViewTo(
                        it.entryCount.toFloat(),
                        value.get(value.size - 1).toFloat(),
                        YAxis.AxisDependency.LEFT
                    )
                }
            }
        }
    }

    fun getDrawableLine(): Drawable {
        return GradientDrawable().also {
            it.shape = GradientDrawable.RECTANGLE
            it.colors = intArrayOf(
                Color.parseColor("#D2F8EA"),
                Color.parseColor("#D2F8EA"),
                Color.parseColor("#E5FBF3"),
                Color.parseColor(
                    "#FEFFFE"
                ),
                Color.WHITE
            )
        }
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.devices_info -> {
                viewModel.cmdExceptions?.let {
                    if (show == null || !show!!.isShowing)
                        show = DialogException.Builder(activity)
                            .setCmdExceptionList(it).show()
                }
            }
            //测试
            R.id.addAction -> {
//                for (i in 0..200) {
//                    emitter.onNext(
//                        SportReceive(
//                            Random.nextInt(3000, 5000),
//                            Random.nextInt(3000, 5000),
//                            Random.nextInt(3000, 5000)
//                        )
//                    )
//                }
//                currentCount = currentCount + 1
//                upDataCount(currentCount)
            }
        }
    }

    override fun onDataReceived(speed: Int, moment: Int, power: Int) {
        //转速
        //力矩
        //功率
//        emitter?.let {
//            if (!subscribe.isDisposed) {
//                it.onNext(SportReceive(speed, moment, power))
//            }
//        }
//        viewModel?.let {
//            HANDLER.post {
//                var countCalories = CmdUntil.countCalories(power)
//                if (countCalories.toDouble() > 0) {
//                    countCalories =
//                        CalcuUtils.getInstance().div(countCalories, 1000.toBigDecimal(), 2)
//                    viewModel.cacheCalories(countCalories)
//                    it.accumulativeCaloriesLiveData.set(
//                        CalcuUtils.getInstance().add(
//                            it.accumulativeCaloriesLiveData.get()!!.toBigDecimal(),
//                            countCalories,
//                            2
//                        ).toPlainString()
//                    )
//                }
//            }
//            setLineData(if (it.chartTypeY == 0) speed else moment)
//            var tempTime = System.currentTimeMillis()
//            if (tempTime - currentTime > spaceTime) {
//                currentTime = tempTime;
//                HANDLER.post {
//                    binding.sportChart.notifyDataSetChanged()
//                }
//            }
//        }
    }


    var show: BaseDialog? = null
    override fun errorList(cmdExceptions: MutableList<CmdException>) {
        viewModel?.let {
            it.cmdExceptions = cmdExceptions
        }
    }

    override fun onPause() {
        super.onPause()
        player?.let {
            it.pausePlay()
        }
    }

    override fun onRestart() {
        super.onRestart()
        backGroup = false
        player?.let {
            it.startPlay()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        player?.let {
            it.pausePlay()
            it.onDestroy()
        }
    }

    override fun upDataCount(count: Int?) {
        HANDLER.post {
            viewModel?.let {
                viewModel.addCurrentCount()
            }
        }

    }
}


